package ru.spb.osll.myfit.wikiverifier.suggester;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.util.StringUtils;
import ru.spb.osll.myfit.wikiverifier.distance.MyFitDistance;

public class SetUpFixtureSuggester implements TemplateSuggester {

	@Override
	public double distance(Table table, Table template) {
		LinkedList<String> tableLines = new LinkedList<String>();
		for (int i = 0; i < Math.min(2, table.getData().size()); i++) {
			tableLines.add(StringUtils.join(table.getData().get(i), "") + " ");
		}

		LinkedList<String> templateLines = new LinkedList<String>();
		for (int i = 0; i < Math.min(2, template.getData().size()); i++) {
			templateLines.add(StringUtils.join(template.getData().get(i), "")  + " ");
		}

		double distance = 0;
		Iterator<String> tableIter = tableLines.iterator();
		Iterator<String> templateIter = templateLines.iterator();
		StringBuffer tableStr = new StringBuffer();
		StringBuffer templateStr = new StringBuffer();

		while (tableIter.hasNext() && templateIter.hasNext()) {
			tableStr.append(tableIter.next());
			tableStr.append(" ");
			templateStr.append(templateIter.next());
			templateStr.append(" ");
		}

		distance = MyFitDistance.calc(tableStr.toString(), templateStr.toString());

		return distance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Table getSuggestion(Table table, Table template) {

		if (table.getData().size() < 2 || template.getData().size() < 2) {
			return template;
		}

		Table templateWithValues = new Table(template.getStyle());
		Iterator<Vector<TableCell>> tableIter = table.getData().iterator();
		Iterator<Vector<TableCell>> templateIter = template.getData().iterator();
		templateWithValues.addLine(templateIter.next());
		Vector<TableCell> templateLine = templateIter.next();
		int numberOfArgs = templateLine.size();
		templateWithValues.addLine(templateLine);
		tableIter.next();
		tableIter.next();

		while (tableIter.hasNext()) {
			Vector<TableCell> tableLine = (Vector<TableCell>) tableIter.next()
					.clone();
			int tableLineSize = tableLine.size();
			tableLine.setSize(numberOfArgs);
			if (tableLineSize < numberOfArgs) {
				for (int i = tableLineSize; i < numberOfArgs; i++) {
					tableLine.set(i, new TableCell(""));
				}
			}
			templateWithValues.addLine(tableLine);
		}

		return templateWithValues;
	}
}
